<template>
  <div>
    <el-form ref="saleInfoList" :model="saleInfoList" label-width="180px" class="sale-info-list">
      <el-tooltip
        class="item"
        effect="dark"
        popper-class="message"
        content="规格名称：用户购买时选择的商品类别，常用的属性:颜色、重量、长度、形状等
规格参数：属性对应下的不同规格，例如:红色、100KG、5米、圆形等"
        placement="top"
      >
        <i style="cursor:pointer;" class="el-icon-warning-outline" />
      </el-tooltip>
      <el-form-item label="自定义商品规格　　：">
        <template v-if="addOrChange">
          <el-form
            v-for="(item,index) in saleInfoList.specsName"
            :key="index"
            ref="specsName"
            class="saleInfoSet"
            :model="item"
            :rules="rules"
          >
            <el-form-item prop="name">
              <el-input
                v-model="item.name"
                placeholder="请输入自定义规格名称"
                clearable
                :disabled="item.new === 0 || !$props.typechecked3"
                @input="specsInput(item.name)"
              />
              <span style="color:#778AAA;cursor:pointer;" @click="removeSpecs(index)">移除</span>
            </el-form-item>
            <el-form-item>
              <autocomplete
                v-for="(param,i) in item.parameter"
                :key="i"
                :position="{id:index,i:i}"
                :suggestions="item.details"
                class="autocomplete"
                :disabled="!$props.typechecked3"
                :input-content="param"
                @selected="getSuggestion"
                @showChangeData="getContentData"
                @deleteShow="deleteShowData"
              />
            </el-form-item>
          </el-form>
        </template>
        <template v-else>
          <el-form
            v-for="(item,index) in saleInfoList.specsName"
            :key="index"
            ref="specsName"
            class="saleInfoSet"
            :model="item"
            :rules="rules"
          >
            <el-form-item prop="name">
              <el-input
                v-model="item.propertys"
                placeholder="请输入自定义规格名称"
                clearable
                :disabled="item.new === 0 || !$props.typechecked3"
                @input="specsInput(item.name)"
              />
              <span style="color:#778AAA;cursor:pointer;" @click="removeSpecs(index)">移除</span>
            </el-form-item>
            <el-form-item>
              <el-input
                v-for="(param,i) in item.propertyValue"
                :key="i"
                v-model="param.item"
                disabled
              />
            </el-form-item>
          </el-form>
        </template>
        <div>
          <el-button class="add-specs-btn" @click="addSpecs()">添加规格</el-button>
          <span style="color:#A8ABB8">&ensp;规格总数最多4组</span>
        </div>
      </el-form-item>
      <el-form-item label="价格与库存：">
        <div class="import-specs">
          <div>在商品规格中输入或选择内容可以进行筛选和批量填充</div>
          <el-link type="primary" :underline="false" @click="tabelData()">批量导入商品规格</el-link>
        </div>
        <table v-if="addOrChange" border="1" style="border-collapse:collapse">
          <tr style="color:#838A9D;">
            <td>商品规格</td>
            <td>规格参数</td>
            <td>价格（元）</td>
            <td>库存</td>
          </tr>
          <tr style="color:#3C4353;">
            <td>
              <p
                v-for="(type,indexId) in saleInfoList.typeCompose"
                :key="indexId"
                class="table-title"
              >{{ indexId===0?makeUpName:'' }}</p>
            </td>
            <td colspan="3" style="padding:0;">
              <div class="table-content">
                <div>
                  <div v-for="(type,indexId) in saleInfoList.typeCompose" :key="indexId">
                    <div
                      class="table-content-param"
                    >{{ type[0]?type[0]:null }}{{ type[1]?'+'+type[1]:null }}{{ type[2]?'+'+type[2]:null }}{{ type[3]?'+'+type[3]:null }}</div>
                    <div style="text-align:center; text-indent:0;">
                      <el-input
                        v-model="type.unitPrice"
                        placeholder="请输入价格"
                        @change="toFixedAddTwo('价格',indexId,type.unitPrice,'saleInfoList.typeCompose')"
                      />
                    </div>
                    <div style="text-align:center; text-indent:0;">
                      <el-input
                        v-model="type.amount"
                        placeholder="请输入库存数量"
                        @change="toFixedAddTwo('数量',indexId,type.amount,'saleInfoList.typeCompose')"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </table>
        <table v-else border="1" style="border-collapse:collapse">
          <tr style="color:#838A9D;">
            <td>商品规格</td>
            <td>规格参数</td>
            <td>价格（元）</td>
            <td>库存</td>
          </tr>
          <tr style="color:#3C4353;">
            <td>
              <p
                v-for="(type,indexId) in returnTable"
                :key="indexId"
                class="table-title"
              >{{ indexId===0?type.propertyName:'' }}</p>
            </td>
            <td colspan="3" style="padding:0;">
              <div class="table-content">
                <div>
                  <div v-for="(type,indexId) in returnTable" :key="indexId">
                    <div class="table-content-param">{{ type.propertyValue }}</div>
                    <div style="text-align:center; text-indent:0;">
                      <el-input
                        v-model="type.unitPrice"
                        placeholder="请输入价格"
                        @change="toFixedAddTwo('价格',indexId,type.unitPrice,'returnTable')"
                      />
                    </div>
                    <div style="text-align:center; text-indent:0;">
                      <el-input
                        v-model="type.amount"
                        placeholder="请输入库存数量"
                        @change="toFixedAddTwo('数量',indexId,type.amount,'returnTable')"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getPropertyValue } from '@/api/goods';
import { mapGetters } from 'vuex';
import autocomplete from '../components/com';
export default {
  components: {
    autocomplete
  },
  props: {
    specifications: {
      type: Array,
      required: true
    },
    typechecked3: {
      type: String,
      required: true
    },
    getdata: {
      type: Object,
      required: true
    }
  },
  data() {
    var checkSpecs = (rule, value, callback) => {
      const arr = [];
      for (let i = 0; i < this.saleInfoList.specsName.length; i++) {
        arr.push(this.saleInfoList.specsName[i].name);
      }

      arr.splice(arr.indexOf(this.specsInputData), 1);
      if (arr.includes(this.specsInputData) && this.specsInputData !== '') {
        callback(123);
        this.$message.error('已有此规格，请勿重复添加');
      }
    };
    return {
      saleInfoList: {
        specsName: [
          {
            name: '',
            parameter: [{ param: '', id: '' }],
            id: 0,
            new: 1,
            details: []
          }
        ],
        typeCompose: [],
        sendServerData: []
      },
      rules: {
        name: [{ validator: checkSpecs, trigger: 'blur' }]
      },
      specsInputData: '',
      makeUpName: '',
      specificationsArray: this.$props.specifications,
      disabled: true,
      addOrChange: true, // true 添加，false 修改
      // 修改回显table
      returnTable: [],
      id: false
    };
  },
  computed: {
    ...mapGetters(['shopInfo'])
  },
  watch: {
    specifications() {
      if (this.$props.specifications[0]) {
        this.saleInfoList.specsName = [];
        this.specificationsArray = this.$props.specifications;
        for (let i = 0; i < this.specificationsArray.length; i++) {
          this.saleInfoList.specsName.push({
            name: this.$props.specifications[i].name,
            id: this.$props.specifications[i].id,
            parameter: [{ param: '', id: '' }],
            details: this.specifications[i].details,
            new: 0
          });
        }
      } else {
        this.saleInfoList.specsName = [
          {
            name: '',
            parameter: [{ param: '', id: '' }],
            id: '',
            details: [],
            new: 1
          }
        ];
      }
    },
    typechecked3() {
    },
    getdata() {
      this.returnTable = this.getdata.saleInfo.table;
      this.saleInfoList.sendServerData = this.getdata.saleInfo.table;
      this.saleInfoList.specsName = this.getdata.saleInfo.propertys;
    }
  },
  created() {
    const id = sessionStorage.getItem('handleEdit');
    if (id && id.length > 1) {
      this.addOrChange = false;
    } else {
      this.addOrChange = true;
    }
  },
  methods: {
    // 规格参数选择后输出
    getSuggestion(item) {
    },
    // 输入框输入后显示与绑定id
    getContentData(value) {
      const id = value.position.id;
      const i = value.position.i;
      const propertyValue = value.id;
      const specs = this.saleInfoList;
      specs.specsName[id].parameter[i].param = value.model;
      specs.specsName[id].parameter[i].id = propertyValue;
      if (
        !specs.specsName[id].parameter[i + 1] &&
        specs.specsName[id].parameter.length < 6
      ) {
        if (specs.specsName[id].parameter[i].param) {
          specs.specsName[id].parameter.push({
            param: '',
            id: ''
          });
        }
      }
    },
    // 删除
    deleteShowData(value) {
      const { id, i } = value;
      const specs = this.saleInfoList;
      specs.specsName[id].parameter.splice(i, 1);
      if (i === specs.specsName[id].parameter.length - 1) {
        if (i === 0) {
          specs.specsName[id].parameter[0].param = '';
          specs.specsName[id].parameter[0].id = '';
        }
      }
    },
    // 添加规格
    addSpecs() {
      if (this.addOrChange) {
        if (this.saleInfoList.specsName.length < 4) {
          this.saleInfoList.specsName.push({
            name: '',
            parameter: [{ param: '', id: '' }],
            id: '',
            details: [],
            new: 1
          });
        }
      } else {
        return;
      }
    },
    // 移除规格
    removeSpecs(id) {
      if (this.addOrChange) {
        if (this.saleInfoList.specsName.length > 1) {
          const specs = this.saleInfoList;
          specs.specsName.splice(id, 1);
        }
      } else {
        return;
      }
    },
    // 点击input自带x删除
    deleteShow(id, i) {},
    // 发送请求获取ID(3)
    sendToGetId(newSpecs) {
      getPropertyValue({ propertys: newSpecs }).then(res => {
        this.specifications = this.specifications;
        for (const item of this.saleInfoList.specsName) {
          item.new = 0;
          for (const resItem of res.data.propertys) {
            if (item.name === resItem.name) {
              item.id = resItem.id;
            }
            for (const itemParameter of item.parameter) {
              for (const resItemDetails of resItem.details) {
                if (itemParameter.param === resItemDetails.propertyValue) {
                  itemParameter.id = resItemDetails.id;
                }
              }
            }
          }
        }
        // 等待Id返回来执行(4)
        this.awaitIdToBack();
      });
    },
    // 验证发送请求(2)
    validateToSend(newSpecs) {
      const specs = this.saleInfoList;
      for (let i = 0; i < specs.specsName.length; i++) {
        if (!specs.specsName[i].parameter[0].param) {
          this.$message.error('第一个规格参数不能为空！');
          return false;
        }
        if (!specs.specsName[i].name) {
          this.$message.error('规格名不能为空！');
          return false;
        }
        if (specs.specsName[i].new === 1) {
          this.sendToGetId(newSpecs);
          return true;
        }
        for (const item of specs.specsName[i].parameter) {
          if (item.id === '' && item.param !== '') {
            this.sendToGetId(newSpecs);
            return true;
          }
        }
      }
      this.awaitIdToBack();
      return true;
    },
    // 点击批量导入规格(1)
    tabelData() {
      if (this.addOrChange) {
        // 调试接口传递新添加的
        const newSpecs = [];
        for (let i = 0; i < this.saleInfoList.specsName.length; i++) {
          if (this.saleInfoList.specsName[i].new === 1) {
            const details = [];
            for (
              let j = 0;
              j < this.saleInfoList.specsName[i].parameter.length;
              j++
            ) {
              if (this.saleInfoList.specsName[i].parameter[j].param) {
                // 第二级传参
                details.push({
                  propertyValue: this.saleInfoList.specsName[i].parameter[j]
                    .param,
                  id: ''
                });
              }
            }
            // 第一级传参
            newSpecs.push({
              name: this.saleInfoList.specsName[i].name,
              shopId: this.shopInfo.id,
              typeId: this.typechecked3,
              id: '',
              details: details
            });
          } else {
            const details = [];
            for (
              let j = 0;
              j < this.saleInfoList.specsName[i].parameter.length;
              j++
            ) {
              if (
                this.saleInfoList.specsName[i].parameter[j].param &&
                this.saleInfoList.specsName[i].parameter[j].id === ''
              ) {
                // 第二级传参
                details.push({
                  propertyValue: this.saleInfoList.specsName[i].parameter[j]
                    .param,
                  id: ''
                });
              }
            }
            for (
              let j = 0;
              j < this.saleInfoList.specsName[i].parameter.length;
              j++
            ) {
              if (
                this.saleInfoList.specsName[i].parameter[j].param &&
                this.saleInfoList.specsName[i].parameter[j].id === ''
              ) {
                // 第一级传参
                newSpecs.push({
                  name: this.saleInfoList.specsName[i].name,
                  shopId: this.shopInfo.id,
                  typeId: this.typechecked3,
                  id: this.saleInfoList.specsName[i].id,
                  details: details
                });
              }
            }
          }
        }
        // 发起请求函数
        if (!this.validateToSend(newSpecs)) return;
        /* ----- */
      } else {
        return;
      }
    },
    // 等待Id返回来执行(4)
    awaitIdToBack() {
      const specs = this.saleInfoList;
      if (this.saleInfoList.specsName.length <= 4) {
        const arr1 = [[], [], [], []];
        const sendServer = [[], [], [], []];
        this.makeUpName = '';
        for (let i = 0; i < specs.specsName.length; i++) {
          if (specs.specsName[i].name) {
            this.makeUpName = this.makeUpName + '+' + specs.specsName[i].name;
            for (let j = 0; j < specs.specsName[i].parameter.length; j++) {
              if (
                specs.specsName[i].parameter[j].param &&
                specs.specsName[i].name
              ) {
                arr1[i][j] = specs.specsName[i].parameter[j].param;
                sendServer[i][j] = specs.specsName[i].parameter[j].id;
              }
            }
          }
        }
        // bug
        for (let i = 0; i < arr1.length; i++) {
          if (!arr1[i][0]) {
            arr1.splice(i);
            sendServer.splice(i);
          }
        }
        const name = this.makeUpName.split('');
        name.shift();
        this.makeUpName = name.join('');
        this.saleInfoList.typeCompose = doCombination(arr1);
        this.saleInfoList.sendServerData = doCombination(sendServer);
      } else {
        this.$message.error('规格总数最多四组！');
      }
      this.saleInfoList.sendServerData = this.saleInfoList.sendServerData.map(
        (value, index) => {
          return { propertyValue: value.join(','), amount: 0, unitPrice: 0 };
        }
      );
      this.$emit('getSaleInfo', this.saleInfoList.sendServerData);
    },
    specsInput(a) {
      this.specsInputData = a;
    },
    // 规格价格和数量验证数字并处理
    toFixedAddTwo(name, index, content, typeCompose) {
      // const typeCompose = this.saleInfoList.typeCompose;
      if (typeCompose === 'returnTable') {
        typeCompose = this.returnTable;
      } else if (typeCompose === 'saleInfoList.typeCompose') {
        typeCompose = this.saleInfoList.typeCompose;
      } else {
        this.$message.error('错误情况');
        return;
      }
      const value = parseFloat(content);
      if (name === '价格') {
        const reg = /^\d+(\.\d+)?$/;
        if (!reg.test(value)) {
          this.$message({
            message: `${name}只能为数字型且为正数！`,
            type: 'error',
            showClose: true,
            duration: 4000
          });
          this.saleInfoList.typeCompose[index].unitPrice = '';
          return false;
        }
        typeCompose[index].unitPrice = parseFloat(value).toFixed(2);
        this.saleInfoList.sendServerData[index].unitPrice = parseFloat(value);
      } else if (name === '数量') {
        const reg = /^\+?[0-9]*$/;
        if (!reg.test(value)) {
          this.$message({
            message: `${name}只能为数字型且为整数！`,
            type: 'error',
            showClose: true,
            duration: 4000
          });
          this.saleInfoList.typeCompose[index].amount = '';
          return false;
        }
        typeCompose[index].amount = parseInt(value);
        this.saleInfoList.sendServerData[index].amount = parseInt(value);
      }
      for (const item of this.saleInfoList.sendServerData) {
        if (item.amount > 0 && item.unitPrice === 0) {
          this.$emit('getSaleInfo', -1);
          return;
        }
      }
      this.$emit('getSaleInfo', this.saleInfoList.sendServerData);
    }
  }
};
// sku
function doCombination(arr) {
  var count = arr.length - 1; // 数组长度(从0开始)
  var tmp = [];
  var totalArr = []; // 总数组
  return doCombinationCallback(arr, 0); // 从第一个开始
  // js 没有静态数据，为了避免和外部数据混淆，需要使用闭包的形式
  function doCombinationCallback(arr, curr_index) {
    for (const val of arr[curr_index]) {
      tmp[curr_index] = val; // 以curr_index为索引，加入数组
      // 当前循环下标小于数组总长度，则需要继续调用方法
      if (curr_index < count) {
        doCombinationCallback(arr, curr_index + 1); // 继续调用
      } else {
        totalArr.push(tmp); // (直接给push进去，push进去的不是值，而是值的地址)
      }

      // js 对象都是 地址引用(引用关系)，每次都需要重新初始化，否则 totalArr的数据都会是最后一次的 tmp 数据；
      var oldTmp = tmp;
      tmp = [];
      for (const index of oldTmp) {
        tmp.push(index);
      }
    }
    return totalArr;
  }
}
</script>

<style lang="scss" scoped>
p {
  padding: 0;
  margin: 0;
}
.sale-info-list {
  padding: 10px 0 15px 16%;
  & > .el-form-item {
    table {
      max-width: 845px;
      border: #e4e9ef;
      background: #fafafe;
      tr {
        td {
          width: 210px;
          height: 55px;
          text-indent: 31px;
          &:first-child {
            text-indent: 0;
            padding-left: 31px;
            line-height: 22px;
          }
          .table-title {
            max-width: 210px;
            word-break: break-all;
            min-height: 55px;
            padding-top: 18px;
            box-sizing: border-box;
          }
          .table-content-param {
            max-width: 210px;
            word-break: break-all;
            line-height: 22px !important;
            text-indent: 0;
            padding-left: 31px;
            min-height: 55px !important;
            display: flex;
            align-items: center;
          }
        }
        .table-content {
          height: 100%;
          width: 100%;
          padding: 0;
          /deep/.el-input__inner {
            width: 160px;
            height: 36px;
            border-radius: 4px;
          }
          & > div:last-child {
            border: 0;
          }
          & > div {
            & > div {
              display: flex;
              justify-content: center;
              align-items: center;
              border-bottom: 1px solid #e4e9ef;
              & > div {
                width: 210px;
                height: 55px;
                line-height: 55px;
                border-right: 1px solid #e4e9ef;
              }
              & > div:nth-child(3n) {
                border-right: 0;
              }
            }
          }
        }
      }
    }
    .saleInfoSet {
      max-width: 780px;
    }
    .add-specs-btn {
      width: 100px;
      height: 32px;
      background: rgba(249, 251, 252, 1);
      border: 1px solid rgba(228, 233, 239, 1);
      color: #1890ff;
      line-height: 32px;
      padding: 0;
    }
    .el-input {
      width: 200px;
      height: 36px;
      margin-bottom: 15px;
      margin-right: 10px;
    }
    .el-autocomplete {
      width: 200px;
      height: 36px;
      margin-bottom: 15px;
      margin-right: 10px;
    }
    .autocomplete {
      display: inline-block;
      width: 200px;
      height: 36px;
      margin-bottom: 15px;
      margin-right: 10px;
    }
  }
  .import-specs {
    color: #838a9d;
    display: flex;
    justify-content: space-between;
    max-width: 842px;
  }
}
.el-icon-warning-outline {
  position: relative;
  right: -133px;
  color: red;
  top: 28px;
}
/deep/.el-input__inner {
  height: 36px;
}
</style>
